package com.lenovo.lcdm.dcm.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lenovo.lcdm.dcm.common.constant.CommonConstant;
import com.lenovo.lcdm.common.enums.CommonMsgEnum;
import com.lenovo.lcdm.common.model.ResponseVo;
import com.lenovo.lcdm.dcm.constant.DcmConstant;
import com.lenovo.lcdm.dcm.dto.DcmTemplateQueryDto;
import com.lenovo.lcdm.dcm.dto.PortfolioOfferingQueryDto;
import com.lenovo.lcdm.dcm.dto.PortfolioOfferingQueryOptionsDto;
import com.lenovo.lcdm.dcm.dto.ReferencedProductInLastYearDto;
import com.lenovo.lcdm.dcm.entity.PortfolioOffering;
import com.lenovo.lcdm.dcm.service.DcmBusinessConfigurationCategoryCService;
import com.lenovo.lcdm.dcm.service.PortfolioOfferingService;
import com.lenovo.lcdm.dcm.service.impl.FeaturesSheetWriteHandler;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther xujing30
 * @Date 2024/01/29
 * @Description
 */
@Slf4j
@RestController
public class PortfolioOfferingController {

    @Autowired
    private PortfolioOfferingService portfolioOfferingService;

    @Autowired
    private DcmBusinessConfigurationCategoryCService businessConfigurationCategoryCService;

    private static final String DEFAULT_GEO = "NA";


    @PostMapping(value = "/portfolio-product", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public ResponseVo<Page<PortfolioOffering>> getPortfolioOffering(@RequestParam(name = "pageNo", required = false, defaultValue = "1") int pageNo, @RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize, @RequestBody PortfolioOfferingQueryDto dto) {
        Page page = new Page(pageNo, pageSize);
        List<PortfolioOffering> data = portfolioOfferingService.getPortfolioOfferingList(page, dto);
        page.setRecords(data);
        return ResponseVo.success(page);
    }

    @GetMapping("/portfolio-product/query-options")
    public ResponseVo<PortfolioOfferingQueryOptionsDto> getQueryOptions() {
        return ResponseVo.success(portfolioOfferingService.getAllQueryOptions());
    }

    @PostMapping("/dcm/template")
    public void downTemplate(HttpServletResponse response, @RequestBody DcmTemplateQueryDto templateDto) throws IOException {
        //模板
        String templatePath = DcmConstant.DCM_KEY_FEATURES_TEMPLATE_PATH;
        //导出文件名
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = templatePath.substring(templatePath.indexOf("/") + 1).replace(".",  "_" + simpleDateFormat.format(new Date())+".");
        InputStream input = null;
        OutputStream outputStream = null;
        try{
            //查询Referenced Product In Last Year页内容
            List<ReferencedProductInLastYearDto> data = portfolioOfferingService.getReferencedProductInLastYear(templateDto.getProductOfferingName());
            //查询category选项范围
            Set<String> categorySet = businessConfigurationCategoryCService.getDistinctCategory();

            input = PortfolioOfferingController.class.getClassLoader().getResourceAsStream(templatePath);
            outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType(CommonConstant.CONTENT_TYPE_XLSX);
            response.setCharacterEncoding(CommonConstant.CHARACTER_ENCODING_UTF8);
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            //写excel
            try(ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(input).build();){
                WriteSheet writeSheet1 = EasyExcel.writerSheet(DcmConstant.SHEET_NAME_REFERENCED_PRODUCT_IN_LAST_YEAR).build();
                excelWriter.fill(data, writeSheet1);
                WriteSheet writeSheet0 = EasyExcel.writerSheet(DcmConstant.SHEET_NAME_FEATURES).registerWriteHandler(new FeaturesSheetWriteHandler(categorySet)).build();
                // 写入geo
                Map<String, String> map = new HashMap<>();
                map.put("geo", DEFAULT_GEO);
                excelWriter.fill(map, writeSheet0);
            }
        }catch (Exception e){
            log.error("Download DCM Key Features Template Failed." + e.getMessage());
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, Object> map = new HashMap<>();
            map.put("code", CommonMsgEnum.FAIL.getCode());
            map.put("message", e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }finally {
            try{
                if(input != null){
                    input.close();
                }
                if(outputStream != null){
                    outputStream.close();
                }
            }catch (IOException e){
                log.error("关闭文件流失败，{}", e.getMessage());
            }
        }
    }

    @GetMapping("/portfolio-product/fetchUserListByUsername")
    public ResponseVo<Object> fetchUserListByUsername(@RequestParam("username") String username) {
        return ResponseVo.success(portfolioOfferingService.fetchUserListByUsername(username));
    }
}
